<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="仓库名称" prop="warehouseName">
        <el-input
          v-model="queryParams.warehouseName"
          placeholder="请输入仓库名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属园区" prop="parkId">
        <el-input
          v-model="queryParams.parkId"
          placeholder="请输入所属园区"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库类型" prop="warehouseType">
        <el-select
          v-model="queryParams.warehouseType"
          placeholder="请选择仓库类型"
          clearable
          filterable
          :loading="optionsLoading"
          style="width: 150px"
        >
          <el-option
            v-for="item in warehouseTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- 新增：是否推荐搜索 -->
      <el-form-item label="是否推荐" prop="isRecommend">
        <el-select v-model="queryParams.isRecommend" placeholder="请选择推荐状态" clearable @change="handleQuery" style="width: 120px">
          <el-option label="推荐" :value="1"></el-option>
          <el-option label="不推荐" :value="0"></el-option>
          <el-option label="全部" :value="null"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:warehouse:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:warehouse:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:warehouse:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:warehouse:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="warehouseList" 
      @selection-change="handleSelectionChange"
      :row-style="{ height: '100px' }"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="warehouseId" />
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="仓库描述" align="center" prop="description" />
      <el-table-column label="详细地址" align="center" prop="address" />
      <el-table-column label="所属园区" align="center" prop="parkId">
        <template slot-scope="scope">
          <span v-if="scope.row.parkInfo.parkName">
            {{ scope.row.parkInfo.parkName }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="仓库类型" align="center" prop="warehouseType">
        <template slot-scope="scope">
          <span v-if="scope.row.warehouseType">
            {{ scope.row.warehouseType.typeName }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="库房面积" align="center" prop="areaSize">
        <template slot-scope="scope">
          <span v-if="scope.row.areaSize !== undefined && scope.row.areaSize !== null && scope.row.areaSize !== ''">
            {{ scope.row.areaSize }} m²
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="地面承重" align="center" prop="floorLoad">
        <template slot-scope="scope">
          <span v-if="scope.row.floorLoad !== undefined && scope.row.floorLoad !== null && scope.row.floorLoad !== ''">
            {{ scope.row.floorLoad }} 吨/m²
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="月台数量" align="center" prop="platformCount">
        <template slot-scope="scope">
          <span v-if="scope.row.platformCount !== undefined && scope.row.platformCount !== null && scope.row.platformCount !== ''">
            {{ scope.row.platformCount }} 个
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="装卸设备配置" align="center" prop="equipmentConfig" />
      <el-table-column label="硬件配置" align="center" prop="hardwareConfig" />
      <el-table-column label="消防等级" align="center" prop="fireLevel" />
      <el-table-column label="消防设施" align="center" prop="fireFacilities" />
      <el-table-column label="安保配置" align="center" prop="security" />
      <el-table-column label="增值服务" align="center" prop="additionalServices" />
      <!-- <el-table-column label="仓库标签" align="center" prop="warehouseTags">
        <template slot-scope="scope">
          <span v-if="scope.row.warehouseTags && Array.isArray(scope.row.warehouseTags)">
            {{ scope.row.warehouseTags.map(item => item.tagName || item.name).join(', ') }}
          </span>
          <span v-else-if="scope.row.warehouseTags">
            {{ scope.row.warehouseTags }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column> -->
      <el-table-column label="地址补充说明" align="center" prop="addressDesc" />
      <el-table-column label="VR全景链接" align="center" prop="vrLink" />
      <el-table-column label="缩略图" align="center" prop="thumbnailUrl" width="100">
        <template slot-scope="scope">
          <el-image 
            v-if="scope.row.thumbnailUrl"
            :src="getFullImageUrl(scope.row.thumbnailUrl)" 
            style="width: 50px; height: 50px;"
            :preview-src-list="[getFullImageUrl(scope.row.thumbnailUrl)]">
          </el-image>
          <span v-else>暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="是否推荐" align="center" prop="isRecommend">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isRecommend"
            :active-value="1"
            :inactive-value="0"
            @change="handleRecommendChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:warehouse:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:warehouse:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


  </div>
</template>

<script>
import { listWarehouse, delWarehouse, updateWarehouse } from "@/api/system/warehouse"
import { listPark } from "@/api/system/park"
import { listPark_tags } from "@/api/system/park_tags"
import { listWarehouse_type } from "@/api/system/warehouse_type"
import { BASE_FILE_URL, BASE_API } from '@/utils/constants'

export default {
  name: "Warehouse",
  data() {
    return {
      // 遮罩层
      loading: true,
      BASE_API: BASE_API, // 添加BASE_API到data中
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓库基础信息表格数据
      warehouseList: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseName: null,
        description: null,
        address: null,
        parkId: null,
        warehouseType: null,
        areaSize: null,
        floorLoad: null,
        platformCount: null,
        equipmentConfig: null,
        hardwareConfig: null,
        fireLevel: null,
        fireFacilities: null,
        security: null,
        additionalServices: null,
        addressDesc: null,
        vrLink: null,
        thumbnailUrl: null,
        isRecommend: null
      },

      // 下拉选项数据
      parkOptions: [],
      tagOptions: [],
      warehouseTypeOptions: [],
      optionsLoading: false,

    }
  },
  async created() {
    this.getList()
    await this.getOptions()
  },
  methods: {
    /** 查询仓库基础信息列表 */
    getList() {
      this.loading = true
      listWarehouse(this.queryParams).then(response => {
        this.warehouseList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取下拉选项数据 */
    async getOptions() {
      if (this.optionsLoading) return; // 防止重复加载
      
      this.optionsLoading = true;
      try {
        // 并行请求下拉选项数据
        const [parkRes, tagRes, typeRes] = await Promise.all([
          listPark(),
          listPark_tags({tagType: 1}),
          listWarehouse_type()
        ]);

        // 处理园区选项
        const parkData = parkRes.rows || parkRes.data || parkRes;
        this.parkOptions = Array.isArray(parkData) ? parkData : [];
        this.parkOptions = this.parkOptions.map(item => ({
          label: item.parkName || item.label || item.name,
          value: item.parkId || item.value || item.id
        }));

        // 处理标签选项
        const tagData = tagRes.rows || tagRes.data || tagRes;
        this.tagOptions = Array.isArray(tagData) ? tagData : [];
        this.tagOptions = this.tagOptions.map(item => ({
          label: item.tagName || item.label || item.name,
          value: item.tagId || item.value || item.id
        }));

        // 处理仓库类型选项
        const typeData = typeRes.rows || typeRes.data || typeRes;
        this.warehouseTypeOptions = Array.isArray(typeData) ? typeData : [];
        this.warehouseTypeOptions = this.warehouseTypeOptions.map(item => ({
          label: item.typeName || item.label || item.name,
          value: item.typeId || item.value || item.id
        }));

      } catch (error) {
        console.error('获取下拉选项数据失败:', error);
      } finally {
        this.optionsLoading = false;
      }
    },
    /** 拼接服务器图片地址 */
    getFullImageUrl(imageUrl) {
      if (!imageUrl) return '';
      // 如果已经是http/https/base64开头，直接返回
      if (/^(http|https):\/\//.test(imageUrl) || imageUrl.startsWith('data:image/')) {
        return imageUrl;
      }
      // 兼容斜杠
      if (imageUrl.startsWith('/')) {
        return this.BASE_API + imageUrl;
      }
      // 默认拼接文件服务器路径
      return BASE_FILE_URL + imageUrl;
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.warehouseId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push('/system/warehouse/add')
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const warehouseId = row.warehouseId || this.ids
      this.$router.push(`/system/warehouse/add?id=${warehouseId}`)
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const warehouseIds = row.warehouseId || this.ids
      this.$modal.confirm('是否确认删除仓库基础信息编号为"' + warehouseIds + '"的数据项？').then(function() {
        return delWarehouse(warehouseIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/warehouse/export', {
        ...this.queryParams
      }, `warehouse_${new Date().getTime()}.xlsx`)
    },
    // 获取园区名称
    getParkName(parkId) {
      const park = this.parkOptions.find(item => item.value === parkId);
      return park ? park.label : parkId;
    },
    // 获取仓库类型名称
    getWarehouseTypeName(typeId) {
      const type = this.warehouseTypeOptions.find(item => item.value === typeId);
      return type ? type.label : typeId;
    },

    // 处理是否推荐状态变化
    handleRecommendChange(row) {
      console.log(row);
      // warehouseTags 转为对象数组 [{ tagId }]
      row.warehouseTags = (
        Array.isArray(row.warehouseTags)
          ? row.warehouseTags.map(tag => ({ tagId: tag.id || tag.tagId || tag }))
          : []
      );
      row.warehouseType = row.warehouseType.typeId || row.warehouseType.id;
      updateWarehouse(row).then(() => {
        this.$modal.msgSuccess("操作成功");
        this.getList();
      }).catch(() => {});
    }
  }
}
</script>


